/*jslint node:true nomen:true*/
'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer');
var fs = require('fs');

app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
app.use(multer({dest: '/tmp/'}).array('image'));

app.get('/indexGet.html', function (req, res) {
    res.sendFile(__dirname + '/' + 'indexGet.html');
});

app.get('/indexPost.html', function (req, res) {
    res.sendFile(__dirname + '/' + 'indexPost.html');
});

app.get('/indexFile.html', function (req, res) {
    res.sendFile(__dirname + '/' + 'indexFile.html');
});

app.post('/upload', function (req, res) {
    console.log(req.files[0]);
    var des_file = __dirname + '/' + req.files[0].originalname;
    fs.readFile(req.files[0].path, function (err, data) {
        if (err) {
            console.error(err);
        }
        fs.writeFile(des_file, data, function (err, data) {
            var response;
            if (err) {
                console.error(err);
            } else {
                response = {
                    message: 'File uploaded successfully',
                    filename: req.files[0].originalname
                };
            }
            console.log(response);
            res.end(JSON.stringify(response));
        });
    });
});

app.post('/process_post', function (req, res) {
    var response = {
        "first_name": req.body.first_name,
        "last_name": req.body.last_name
    };
    console.log(response);
    res.end(JSON.stringify(response));
});

app.get('/process_get', function (req, res) {
    var response = {
        "first_name": req.query.first_name,
        "last_name": req.query.last_name
    };
    console.log(response);
    res.end(JSON.stringify(response));
});

var server = app.listen(8888, function () {
    var host = server.address().address,
        port = server.address().port;
    console.log('应用实例，访问地址为 http://%s:%s', host, port);
});